<template>
  <div  class="BoxChart">
        <div class="BoxChart_title">
            <Card :style="active">
                <div slot="title">
                <div style="margin-bottom:5px">{{chartconfig[indexID].name}}
                     <Poptip trigger="hover"  placement="top-start">
                            <Icon type="ios-paper-outline" style="margin-left:5px"/>
                            <span slot="content" :style="isColor">{{chartconfig[indexID].remark==''?"暂无备注":chartconfig[indexID].remark}}</span>
                    </Poptip>
                </div>
                <div style="font-size:12px">
                    <span>{{date}}</span>
                    <span v-if="JSON.parse(chartconfig[indexID].time).type=='relative'" class="vertical">|</span>
                    <span v-if="JSON.parse(chartconfig[indexID].time).type=='relative'">{{dynamicTime}}</span>
                </div>
                </div>
                <a href="#" slot="extra">
                    <Dropdown trigger="click" >
                        <a href="javascript:void(0)">
                            <i type="md-close" class="del iconfont icon-gengduo"  size="20"></i>
                        </a>
                        <Dropdown-menu slot="list" style="width:100px">
                            <Dropdown-item :selected='chartconfig[indexID].size=="small"' @click.native='setWindow("small")'>小</Dropdown-item>
                            <Dropdown-item :selected='chartconfig[indexID].size=="normal"'  @click.native='setWindow("normal")'>中</Dropdown-item>
                            <Dropdown-item  disabled>大</Dropdown-item>
                            <Dropdown-item  @click.native="set()" divided >设置</Dropdown-item>
                            <Dropdown-item  @click.native="delCharts(chartconfig[indexID].id)">删除</Dropdown-item>
                        </Dropdown-menu>
                    </Dropdown>
                </a>
                <div class="content" :style="place">
                    <div>
                         <span>{{numberDate}}</span>
                         <span v-if="JSON.parse(chartconfig[indexID].time).unit=='day'">({{weekday}})</span>
                         <span v-if="JSON.parse(chartconfig[indexID].time).unit=='week'">{{weekday}}</span>
                         <span v-if="JSON.parse(chartconfig[indexID].time).unit=='month'">{{monthday}}</span>
                    </div>
                    <div class="hers-left">
                        <div>
                            <span class="num">10</span>
                            <span>次</span>
                        </div>
                        <div class="bijiao">
                            <div>环比
                                <!-- <Tooltip placement="top"> -->
                                    <!-- <div slot="content">
                                        <p>Display multiple lines of information</p>
                                    </div> -->
                                    <span :style="bijiaoColor">
                                        <Icon type="md-arrow-dropdown" color='red' size='18' v-if="month_on_month<0" />
                                        <Icon type="md-arrow-dropup" color='#50BB4C' size='18' v-if="month_on_month>0"/>
                                        {{month_on_month}}%
                                    </span>
                                 <!-- </Tooltip> -->
                            </div>
                            <div>同比
                                <!-- <Tooltip placement="top"> -->
                                    <!-- <div slot="content">
                                        <p>Display multiple lines of information</p>
                                    </div> -->
                                    <span :style="bijiaoColor">
                                        <Icon type="md-arrow-dropdown" color='red' size='18' v-if="year_on_year<0" />
                                        <Icon type="md-arrow-dropup" color='#50BB4C' size='18' v-if="year_on_year>0"/>
                                        {{year_on_year}}%
                                    </span>
                                <!-- </Tooltip> -->
                            </div>
                        </div>
                    </div>
                    <div class="statistics-right" v-if="chartconfig[indexID].size !=='small'">
                        <div>
                            <span>合计</span>
                            <span class="num1">{{total}}</span>
                            <span>次</span>
                        </div>
                        <div>
                            <span>均值</span>
                            <span class="num1">{{average}}</span>
                            <span>次</span>
                        </div>
                    </div>
                </div>
            </Card>
        </div>
    </div>
</template>

<script type="text/ecmascript-6">
import setModule from '../components/setModule'
  export default {
    components:{
        setModule
    },
    props:['chartconfig','indexID','dashboardId',"projectId"],
    data() {
        return {
            date:'',
            month_on_month:null,//同比数据
            year_on_year:null,//环比数据
            total:null,//合计
            average:null,//平均
            active1:'height:175px',
            active2:'height:350px',
            place1:'margin-top:10px',
            place2:'margin-top:80px',
            bijiaoColor1:'color:red',
            bijiaoColor2:'color:#50BB4C',
            dynamicTime:'',
            numberDate:'',
            weekday:'',
            monthday:''
        }
    },
    mounted(){
        let _that=this
        let times=JSON.parse(_that.chartconfig[_that.indexID].time)
            if(times.type == 'absolute'){
                times.values[0]=_that.$sessionStore.getDay(-times.values[0])
                times.values[1]=_that.$sessionStore.getDay(-times.values[1])
                _that.date=times.values[0]+"~"+times.values[1]
            }else if(times.type == 'relative'){
                _that.date=times.values[0]+"~"+times.values[1]
                let newdata1=this.dateDiff(times.values[0])
                let newdata2=this.dateDiff(times.values[1])
                if(this.$sessionStore.getDay(0)==times.values[1]&&this.$sessionStore.getDay(0)!==times.values[0]){
                    this.dynamicTime='最近'+newdata1+'天'
                }else if(this.$sessionStore.getDay(0)==times.values[1]&&this.$sessionStore.getDay(0)==times.values[0]){
                     this.dynamicTime='今日'
                }else {
                    this.dynamicTime='过去'+newdata2+'天~过去'+newdata1+'天'
                }
            }
            if(times.unit=='day'){
                this.numberDate=times.values[1].slice(5,10)
                this.weekday=this.getweekday(times.values[1])
            }else if(times.unit=='week'){
                let date=new Date(times.values[1]) 
                let time=Date.parse(date)
                if(this.isWeek(time)){
                   this.weekday='本周'
                }else{
                    this.numberDate=times.values[1].slice(5,10)
                    this.weekday='当周'
                }
            }else if(times.unit=='month'){
                if(this.isMonth(times.values[1])){
                    this.monthday='本月'
                }else{
                    this.monthday=times.values[1].slice(5,7)+'月'
                }
            }
        let timeQuantum={}
        timeQuantum.start=times.values[0]
        timeQuantum.end=times.values[1]
        timeQuantum.unit=times.unit
        timeQuantum.config=_that.chartconfig[_that.indexID].config
        _that.getBiJiao(timeQuantum)
        _that.getaverage(timeQuantum)
           
    },
    computed:{
        isColor:function(){
            if(this.chartconfig[this.indexID].remark==''){
                return "color:#BFBFCD"
            }
        },
        active:function(){
            return this.chartconfig[this.indexID].size=="small"?this.active1:this.active2
        },
        place:function(){
             return this.chartconfig[this.indexID].size=="small"?this.place1:this.place2
        },
        bijiaoColor:function(){
            return this.month_on_month<0?this.bijiaoColor1:this.bijiaoColor2
        }
    },
    methods:{
        getweekday :function(date){
            var weekArray = new Array("日", "一", "二", "三", "四", "五", "六");
            var week = weekArray[new Date(date).getDay()]
            return week;
            },
        dateDiff : function(sDate1) {
                var date2 = new Date();
                var date1 = new Date(Date.parse(sDate1.replace(/-/g,   "/")));
                var iDays = parseInt(Math.abs(date2.getTime()- date1.getTime()) /1000/60/60/24); 
                return iDays;
        },
        isWeek:function (time){
            // 当前时间
            var timestamp = Date.parse(new Date());
            var serverDate = new Date(timestamp);
            //本周周日的的时间
            var sundayTiem = timestamp + ((7 - serverDate.getDay())* 24 * 60 * 60 * 1000)
            var SundayData = new Date(sundayTiem);
            //年
            var tomorrowY = SundayData.getFullYear();
            //月
            var tomorrowM = (SundayData.getMonth() + 1 < 10 ? '0' + (SundayData.getMonth() + 1) : SundayData.getMonth() + 1);
            //日
            var tomorrowD = SundayData.getDate() < 10 ? '0' + SundayData.getDate() : SundayData.getDate();       
            // 本周周一的时间
            var mondayTime = timestamp - ((serverDate.getDay()-1) * 24 * 60 * 60 * 1000)
            var mondayData = new Date(mondayTime);
            //年                   
            var mondayY = mondayData.getFullYear();                    
            //月                   
            var mondayM = (mondayData.getMonth() + 1 < 10 ? '0' + (mondayData.getMonth() + 1) : mondayData.getMonth() + 1);                   
            //日
            var mondayD = mondayData.getDate() < 10 ? '0' + mondayData.getDate() : mondayData.getDate();                   
            // 当前时间                   
            var currentData = new Date(time);                   
            //年                   
            var currentY = currentData.getFullYear();                    
            //月                    
            var currentM = (currentData.getMonth() + 1 < 10 ? '0' + (currentData.getMonth() + 1) : currentData.getMonth() + 1);                   
            //日                   
            var currentD = currentData.getDate() < 10 ? '0' + currentData.getDate() : currentData.getDate();                   
            //时                   
            var currenH = currentData.getHours();                    
            //分                   
            var currenM = currentData.getMinutes();                    
            var str = "星期" + "日一二三四五六".charAt(currentData.getDay());                    
            var sundayDay = tomorrowY + tomorrowM + tomorrowD;                  
            var mondayDay = mondayY + mondayM + mondayD;                   
            var currentDay = currentY + currentM + currentD;                   
            parseInt(currentDay);                   
            parseInt(mondayDay);                    
            if (parseInt(currentDay) >= parseInt(mondayDay)) {                    
              if (parseInt(currentDay) <= parseInt(sundayDay)){                    
                  return true                   
                }else {                   
                return false                  
                }                   
            }else {                  
              return false
                    }
        },
        isMonth:function(date) {    
            var date1 = new Date(date.replace(/-/g, "/"));         //将传入的时间字符串转换成时间对象    
            var date2 = new Date();     　　　　   //当前时间    
            var curDay = date2.getDate();           //获取当前几号    
            var firstDay = this.GetDate((curDay), 1);                                //计算出当月第一天    
            var lastDay = this.GetDate((this.getDaysInMonth(date2.getFullYear(), date2.getMonth() + 1) - curDay), 2);    //计算出当月最后一天
            if (date1.getTime() < firstDay.getTime() || date1.getTime() > lastDay.getTime()) {        
                return false;       //不在同一个月内    
                } else {        
                return true;        //在同一个月内    
                    }
        },
        getDaysInMonth:function(year, month){    
            month = parseInt(month, 10) + 1;    
            var temp = new Date(year + "/" + month + "/0");    
            return temp.getDate();
        },
        GetDate:function(day, type) {    
            var zdate = new Date();    
            var edate;    
            if (type == 1) {        
            edate = new Date(zdate.getTime() - (day * 24 * 60 * 60 * 1000));    
            } else {        
            edate = new Date(zdate.getTime() + (day * 24 * 60 * 60 * 1000));   
            }    
            return edate;
        },
        //匹配measure计算合计和平均值
        getaverage(timeQuantum){
            let _that=this
            _that.$axios.post(_that.$api.report +'/v2/analysis/event',
            timeQuantum,
            {
                headers: {
                    "Authorization": "Bearer "+_that.$sessionStore.fetch(),
                    'Content-type': 'application/json'
                },
                params: {
                    projectId: _that.$store.state.projectId
                 }
                }
            ).then(function(res){
                if(res.status==200){
                    let data=res.data
                    let config=JSON.parse(_that.chartconfig[_that.indexID].config)
                    let joint=[]
                    let AllNumerical=[]
                    for (let i=0;i<config.indicators[0].measure.length; i++){
                        joint.push(config.indicators[0].event+"_"+config.indicators[0].measure[i].name)
                    }
                    for(let j=0;j<data.length;j++){
                        for(var key in data[j]){
                            for(let o=0;o<joint.length;o++){
                                if(key==joint[o]){
                                    AllNumerical.push(data[j][key])
                                }
                            }
                        }
                    }
                    _that.total=eval(AllNumerical.join("+"))
                    _that.average=Math.round(_that.total/AllNumerical.length)
                 
                }
            }).catch(function(err){
                console.log(err);
            })

        },
        // 获取同比环比数据
        getBiJiao(timeQuantum){
            let _that=this
            _that.$axios.post(_that.$api.report +'/analysis/event/compare',
            timeQuantum,
            {
                headers: {
                    "Authorization": "Bearer "+_that.$sessionStore.fetch(),
                    'Content-type': 'application/json'
                },
                params: {
                    projectId: _that.$store.state.projectId
                 }
                }
            ).then(function(res){
                if(res.status==200){
                    _that.month_on_month=res.data.month_on_month
                    _that.year_on_year=res.data.year_on_year
                }
            }).catch(function(err){
                console.log(err);
            })
        },

        set(){
           this.$parent.$parent.$parent.$parent.updatamodal2(this.indexID,'set')
        },
        setWindow(col){
            this.$parent.$parent.$parent.$parent.changeSize(this.indexID,col)
        },
        delCharts(del_id){
            let _that = this;
            this.$axios.delete(_that.$api.report +'/dashboard-pro/'+_that.dashboardId[0].id+'/block/'+del_id,
                {
                    headers: {
                        "Authorization": "Bearer "+this.$sessionStore.fetch(),
                        'Content-type': 'application/json'
                    },
                    params: {
                        projectId:_that.projectId
                    }
                }
            )
            .then(function(res){
                _that.$Message.info('删除成功');
                _that.chartconfig.map((item,index)=>{
                    if(item.id == del_id){
                        _that.chartconfig.splice(index,1);
                    }
                    return true; 
                })
            }).catch(function(err){
                console.log(err);
            })
        },
    }
  }
</script>

<style  scoped>
.vertical{
    font-weight: 700;
    margin: 0 5px;
}
.BoxChart{
    margin-top:10px;
}
.hers-left{
        float: left;
        display: flex;
        color: #BAC1CD
    } 
.num{
        font-size: 32px;
        color: #475669;
        font-weight: 700
    }
.bijiao{
    margin-left:10px; 
}
.statistics-right{
    margin-right: 30px;
    color: #BAC1CD;
    float: right;
    border-left:1px solid #E9F0F7;
    width: 150px;
    padding-left:30px;
    margin-top: -7px;
}
.num1{
    color: #475669;
    font-size: 16px
}

</style>
